package client.comm.baoding.adapter

import android.content.Context
import android.content.Intent
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import client.comm.commlib.base.BaseLoadmoreAdapter
import client.comm.commlib.base.BindingViewHoder
import client.comm.baoding.R
import client.comm.baoding.api.bean.GoodsIndex
import client.comm.baoding.api.bean.SeartchRet
import client.comm.baoding.databinding.LayoutSearchretitemBinding
import client.comm.baoding.ui.GoodsDetailActivity
import com.bumptech.glide.RequestManager


class SearchRetAdapter : BaseLoadmoreAdapter<SeartchRet.Goods> {

    val manager: RequestManager
    lateinit var goodsIndex: GoodsIndex

    constructor(context: Context, manager: RequestManager) : super(context,
        object : DiffUtil.ItemCallback<SeartchRet.Goods>() {
            override fun areItemsTheSame(
                oldItem: SeartchRet.Goods,
                newItem: SeartchRet.Goods
            ): Boolean {
                return oldItem != null && newItem != null && oldItem.equals(newItem)
            }

            override fun areContentsTheSame(
                oldItem: SeartchRet.Goods,
                newItem: SeartchRet.Goods
            ): Boolean {
                return oldItem == newItem
            }
        }) {
        this.manager = manager
    }

    override fun createVh(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        return BindingViewHoder(
            DataBindingUtil.inflate(
                layoutInflater,
                R.layout.layout_searchretitem,
                parent,
                false
            )
        )
    }

    override fun bindVh(holder: RecyclerView.ViewHolder, position: Int) {
        val bindingViewHolder = holder as BindingViewHoder<ViewDataBinding>
        val binding = bindingViewHolder.binding as LayoutSearchretitemBinding

        val bean = getItem(position)
        binding.bean = bean
        manager.load(bean.goods_img)
            .into(binding.img)
        binding.event = this
    }

    override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) {
        super.onViewAttachedToWindow(holder)
        super.onViewAttachedToWindow(holder)
        val lp: ViewGroup.LayoutParams = holder.itemView.getLayoutParams()
        if (lp != null && lp is StaggeredGridLayoutManager.LayoutParams
            && holder.getItemViewType() === 2
        ) {
            val p = lp as StaggeredGridLayoutManager.LayoutParams
            p.isFullSpan = true
        }
    }

    fun itemClick(bean: SeartchRet.Goods) {
        context.startActivity(Intent(context, GoodsDetailActivity::class.java).apply {
            putExtra("goodsId", "${bean.goods_id}")
        })
    }
}